package gold.digger;

import java.util.*;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC227 {
    public long startExecuteTime = System.currentTimeMillis();

    public int calculate(String str) {
        long curNum = 0;
        Deque<Integer> numQueue = new LinkedList<>();
        Deque<Character> opQueue = new LinkedList();

        for (int i = 0; i < str.length(); i++) {
            char cur = str.charAt(i);
            if (cur == ' ') {
                continue;
            }

            if (cur <= '9' && cur >= '0') {
                curNum = curNum * 10 + cur - '0';
                continue;
            }

            if (cur == '*' || cur == '/') {
                int nextOpNum = 0;
                while (++i < str.length()) {
                    if (str.charAt(i) == ' ') continue;
                    if (!(str.charAt(i) >= '0' && str.charAt(i) <= '9')) {
                        --i;
                        break;
                    }

                    nextOpNum = nextOpNum * 10 + str.charAt(i) - '0';
                }

                curNum = cur == '*' ? curNum * nextOpNum : curNum / nextOpNum;
                continue;
            }

            if (cur == '+' || cur == '-') {
                numQueue.offer(((int) curNum));
                opQueue.offer(cur);
                curNum = 0;
                continue;
            }
        }

        numQueue.offer(((int) curNum));
        while (!opQueue.isEmpty()) {
            char op = opQueue.pop();
            int left = numQueue.pop();
            int right = numQueue.pop();
            curNum = op == '+' ? left + right : left - right;
            numQueue.addFirst(((int) curNum));
        }

        return ((int) curNum);
    }


    public static void main(String[] args) {
        LC227 an = new LC227();
        String test = "1+1-1";
        System.out.println(an.calculate(test));

        System.out.println("\nanswer total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
